package com.example.capsule.service;

import com.example.capsule.entity.Capsule;
import com.example.capsule.entity.Invitation;
import com.example.capsule.entity.User;
import com.example.capsule.repository.CapsuleRepository;
import com.example.capsule.repository.InvitationRepository;
import com.example.capsule.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class InvitationService {

    @Autowired
    private InvitationRepository invitationRepository;
    @Autowired
    private CapsuleRepository capsuleRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private NotificationService notificationService;
    @Autowired
    private SmsService smsService;

    /**
     * 发送邀请通知（更新版）
     */
    private void sendInvitationNotification(String senderPhone, String recipientPhone, Invitation invitation) {
        // 生成指向邀请页面的链接，而不是直接指向API
        String inviteUrl = "https://expensive-monroe-moms-revenues.trycloudflare.com/invitation?token=" + invitation.getInviteToken();

        String senderName = userRepository.findByPhone(senderPhone)
                .map(User::getNickname)
                .orElse(senderPhone);

        String capsuleTitle = capsuleRepository.findById(invitation.getCapsuleId())
                .map(Capsule::getTitle)
                .orElse("时光胶囊");

        String message = String.format("%s邀请您查看时光胶囊《%s》，点击链接接受：%s（7天内有效）",
                senderName, capsuleTitle, inviteUrl);

        sendSmsInvitation(recipientPhone, message);
    }
    /**
     * 发送短信邀请
     */
    private void sendSmsInvitation(String phone, String message) {
        try {
            // 使用阿里云短信服务发送
            // 这里需要根据你的短信模板进行调整
            System.out.println("发送邀请短信到: " + phone);
            System.out.println("短信内容: " + message);

            // 模拟发送（实际项目中应该调用阿里云短信服务）
            System.out.println("=== 短信邀请 ===");
            System.out.println("收件人: " + phone);
            System.out.println("内容: " + message);
            System.out.println("==================");

        } catch (Exception e) {
            System.err.println("发送短信邀请失败: " + e.getMessage());
            // 失败时使用控制台输出
            System.out.println("短信发送失败，请手动通知: " + phone + " - " + message);
        }
    }
    /**
     * 创建邀请（基于手机号）
     */
    public Invitation createInvitation(Long capsuleId, String senderPhone, String recipientPhone) {
        // 验证发送者权限
        Optional<Capsule> capsuleOpt = capsuleRepository.findById(capsuleId);
        if (capsuleOpt.isEmpty()) {
            throw new RuntimeException("胶囊不存在");
        }
        Capsule capsule = capsuleOpt.get();
        if (!capsule.getSenderPhone().equals(senderPhone)) {
            throw new RuntimeException("无权操作此胶囊");
        }

        // 验证接收者手机号格式
        if (!smsService.isValidPhone(recipientPhone)) {
            throw new RuntimeException("接收者手机号格式不正确");
        }

        // 检查是否已经邀请过
        Optional<Invitation> existingInvitation = invitationRepository
                .findByCapsuleIdAndRecipientPhone(capsuleId, recipientPhone);
        if (existingInvitation.isPresent()) {
            Invitation existing = existingInvitation.get();
            if (existing.isPending()) {
                throw new RuntimeException("已经邀请过该用户，邀请待处理中");
            } else if (existing.isAccepted()) {
                throw new RuntimeException("该用户已经接受了邀请");
            }
        }

        // 创建邀请（但不发送短信）
        Invitation invitation = new Invitation();
        invitation.setCapsuleId(capsuleId);
        invitation.setRecipientPhone(recipientPhone);
        invitation.setInviteToken(generateInviteToken());
        invitation.setStatus("PENDING");
        invitation.setCreatedAt(LocalDateTime.now());
        invitation.setExpiresAt(LocalDateTime.now().plusDays(7));

        invitation = invitationRepository.save(invitation);
        System.out.println("邀请创建成功（延迟发送短信）");

        return invitation;
    }



    /**
     * 接受邀请（基于手机号）- 修改验证逻辑
     */
    // 最小化修改 acceptInvitation 方法
    public boolean acceptInvitation(String token, String userPhone) {
        Optional<Invitation> invitationOpt = invitationRepository.findByInviteToken(token);
        if (invitationOpt.isEmpty()) {
            return false; // 邀请不存在
        }

        Invitation invitation = invitationOpt.get();

        // 移除状态检查，允许重复查看
        // if (!"PENDING".equals(invitation.getStatus())) {
        //     return false; // 邀请已被处理
        // }

        // 检查是否过期
        if (invitation.isExpired()) {
            invitation.setStatus("EXPIRED");
            invitationRepository.save(invitation);
            return false;
        }

        Optional<Capsule> capsuleOpt = capsuleRepository.findById(invitation.getCapsuleId());
        if (capsuleOpt.isEmpty()) {
            return false;
        }

        Capsule capsule = capsuleOpt.get();

        // 只有当状态是PENDING时才更新胶囊和邀请状态
        if ("PENDING".equals(invitation.getStatus())) {
            capsule.setRecipientPhone(userPhone);
            capsuleRepository.save(capsule);

            invitation.setStatus("ACCEPTED");
            invitation.setAcceptedAt(LocalDateTime.now());
            invitationRepository.save(invitation);

            sendAcceptanceNotification(capsule.getSenderPhone(), userPhone, capsule.getTitle());
        }

        return true; // 总是返回true，允许查看
    }
    /**
     * 发送接受通知
     */
    private void sendAcceptanceNotification(String senderPhone, String recipientPhone, String capsuleTitle) {
        try {
            System.out.println("=== 邀请接受通知 ===");
            System.out.println("发送者: " + senderPhone);
            System.out.println("内容: " + recipientPhone + "已接受您的时光胶囊《" + capsuleTitle + "》邀请");
            System.out.println("==================");
        } catch (Exception e) {
            System.err.println("发送接受通知失败: " + e.getMessage());
        }
    }

    // 添加新方法
    public Optional<Invitation> getInvitationByToken(String token) {
        return invitationRepository.findByInviteToken(token);
    }

    /**
     * 获取用户的邀请列表
     */
    public List<Invitation> getUserInvitations(String userPhone) {
        return invitationRepository.findByRecipientPhone(userPhone);
    }

    /**
     * 获取待处理的邀请数量
     */
    public long getPendingInvitationCount(String userPhone) {
        return invitationRepository.countByRecipientPhoneAndStatus(userPhone, "PENDING");
    }

    /**
     * 检查用户是否有待处理的邀请
     */
    public boolean hasPendingInvitations(String userPhone) {
        return invitationRepository.existsByRecipientPhoneAndStatus(userPhone, "PENDING");
    }

    /**
     * 获取胶囊的所有邀请
     */
    public List<Invitation> getCapsuleInvitations(Long capsuleId, String userPhone) {
        // 验证用户权限
        Optional<Capsule> capsuleOpt = capsuleRepository.findById(capsuleId);
        if (capsuleOpt.isEmpty() || !capsuleOpt.get().getSenderPhone().equals(userPhone)) {
            throw new RuntimeException("无权查看此胶囊的邀请");
        }

        return invitationRepository.findByCapsuleId(capsuleId);
    }

    /**
     * 取消邀请
     */
    public boolean cancelInvitation(Long invitationId, String userPhone) {
        Optional<Invitation> invitationOpt = invitationRepository.findById(invitationId);

        if (invitationOpt.isEmpty()) {
            return false;
        }

        Invitation invitation = invitationOpt.get();

        // 验证权限（只有发送者可以取消）
        Optional<Capsule> capsuleOpt = capsuleRepository.findById(invitation.getCapsuleId());
        if (capsuleOpt.isEmpty() || !capsuleOpt.get().getSenderPhone().equals(userPhone)) {
            throw new RuntimeException("无权取消此邀请");
        }

        // 只能取消待处理的邀请
        if (!"PENDING".equals(invitation.getStatus())) {
            throw new RuntimeException("只能取消待处理的邀请");
        }

        invitation.setStatus("CANCELLED");
        invitationRepository.save(invitation);

        return true;
    }

    /**
     * 重新发送邀请
     */
    public boolean resendInvitation(Long invitationId, String userPhone) {
        Optional<Invitation> invitationOpt = invitationRepository.findById(invitationId);

        if (invitationOpt.isEmpty()) {
            return false;
        }

        Invitation invitation = invitationOpt.get();

        // 验证权限
        Optional<Capsule> capsuleOpt = capsuleRepository.findById(invitation.getCapsuleId());
        if (capsuleOpt.isEmpty() || !capsuleOpt.get().getSenderPhone().equals(userPhone)) {
            throw new RuntimeException("无权重新发送此邀请");
        }

        // 只能重新发送已过期或已取消的邀请
        if (!"EXPIRED".equals(invitation.getStatus()) && !"CANCELLED".equals(invitation.getStatus())) {
            throw new RuntimeException("只能重新发送已过期或已取消的邀请");
        }

        // 更新邀请信息
        invitation.setStatus("PENDING");
        invitation.setInviteToken(generateInviteToken());
        invitation.setCreatedAt(LocalDateTime.now());
        invitation.setExpiresAt(LocalDateTime.now().plusDays(7));
        invitationRepository.save(invitation);

        // 重新发送通知
        sendInvitationNotification(userPhone, invitation.getRecipientPhone(), invitation);

        return true;
    }

    /**
     * 生成邀请令牌
     */
    private String generateInviteToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 定时清理过期邀请
     *//*
    @Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行
    public void cleanupExpiredInvitations() {
        List<Invitation> expiredInvitations = invitationRepository.findByStatusAndExpiresAtBefore(
                "PENDING", LocalDateTime.now());

        for (Invitation invitation : expiredInvitations) {
            invitation.setStatus("EXPIRED");
        }

        if (!expiredInvitations.isEmpty()) {
            invitationRepository.saveAll(expiredInvitations);
            System.out.println("清理了 " + expiredInvitations.size() + " 个过期邀请");
        }
    }*/

    /**
     * 获取邀请详情
     */
    public Optional<Invitation> getInvitationDetail(Long invitationId, String userPhone) {
        Optional<Invitation> invitationOpt = invitationRepository.findById(invitationId);

        if (invitationOpt.isEmpty()) {
            return Optional.empty();
        }

        Invitation invitation = invitationOpt.get();

        // 验证权限（发送者或接收者可以查看）
        Optional<Capsule> capsuleOpt = capsuleRepository.findById(invitation.getCapsuleId());
        boolean isSender = capsuleOpt.isPresent() && capsuleOpt.get().getSenderPhone().equals(userPhone);
        boolean isRecipient = invitation.getRecipientPhone().equals(userPhone);

        if (!isSender && !isRecipient) {
            throw new RuntimeException("无权查看此邀请");
        }

        return invitationOpt;
    }

    // 在InvitationService类中添加
    public Map<String, Object> getInvitationDetailInfo(String token) {
        Map<String, Object> info = new HashMap<>();

        Optional<Invitation> invitationOpt = invitationRepository.findByInviteToken(token);
        if (invitationOpt.isEmpty()) {
            info.put("error", "邀请不存在");
            return info;
        }

        Invitation invitation = invitationOpt.get();
        info.put("intendedRecipient", invitation.getRecipientPhone());
        info.put("capsuleId", invitation.getCapsuleId());
        info.put("status", invitation.getStatus());
        info.put("expired", invitation.isExpired());

        // 获取胶囊信息
        Optional<Capsule> capsuleOpt = capsuleRepository.findById(invitation.getCapsuleId());
        capsuleOpt.ifPresent(capsule -> {
            info.put("senderPhone", capsule.getSenderPhone());
            info.put("capsuleTitle", capsule.getTitle());
        });

        return info;
    }
}